package com.aos.erp.generator.service.impl;

import com.aos.erp.common.bean.IPageBean;
import com.aos.erp.generator.mapper.GeneratorMapper;
import com.aos.erp.generator.service.GeneratorService;
import com.aos.erp.generator.utils.GeneratorUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

@Service
public class GeneratorServiceImpl implements GeneratorService {
    @Resource
    private GeneratorMapper mapper;

    @Override
    public IPageBean<Map<String, Object>> queryList(long page, long size, String name) {
        IPage pageParam = mapper.createPlusPage(page, size);
        List list = mapper.selectPage(pageParam, name);
        pageParam.setRecords(list);
        return mapper.toBizPage(pageParam);
    }

    @Override
    public Map<String, String> queryTable(String tableName) {
        return mapper.queryTable(tableName);
    }

    @Override
    public List<Map<String, String>> queryColumns(String tableName) {
        return mapper.queryColumns(tableName);
    }


    @Override
    public byte[] generatorCode(String packageName, String moduleName, String[] tableNames,String tablePrefix) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GeneratorUtils.generatorCode(packageName, moduleName, table, columns, zip,tablePrefix);
        }


        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
